package com.itheima.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.mapper.GoodsDao;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.service.GoodsService;
import com.itheima.goods.vo.ResultInfo;
import entity.PageResult;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao,Goods> implements GoodsService {
    @Autowired
    private GoodsDao goodsDao;

    @Override
    public ResultInfo findAll() {
        List<Goods> goods =  goodsDao.selectList(null);
        if (goods!=null && goods.size()>0) {
            return new ResultInfo().builder().code(StatusCode.OK).data(goods).message("查询成功").flag(true).build();
        }
        return new ResultInfo().builder().message("查询失败").code(StatusCode.ERROR).flag(false).build();
    }

    @Override
    public ResultInfo add(Goods goods) {
        Integer result = goodsDao.insert(goods);
        if (result!=null && result==1) {
            return new ResultInfo().builder().code(StatusCode.OK).message("添加成功").flag(true).build();
        }
        return new ResultInfo().builder().code(StatusCode.ERROR).message("添加失败").flag(false).build();
    }

    @Override
    public ResultInfo findPage(Integer page, Integer size) {
        IPage<Goods> goodsPage = new Page<>(page,size);
        goodsDao.selectPage(goodsPage,null);
        List<Goods> records = goodsPage.getRecords();
        if (records!=null && records.size()>0) {
            return new ResultInfo().builder().code(StatusCode.OK).data(new PageResult<Goods>((long) records.size(),records)).message("查询成功").flag(true).build();
        }
        return new ResultInfo().builder().code(StatusCode.ERROR).message("查询失败或暂无数据").flag(false).build();
    }

    @Override
    public ResultInfo findById(Integer id) {
        Goods goods = goodsDao.selectById(id);
        if (goods!=null) {
            return new ResultInfo().builder().code(StatusCode.OK).data(goods).message("查询成功").flag(true).build();
        }
        return new ResultInfo().builder().code(StatusCode.ERROR).message("查询失败或暂无数据").flag(false).build();
    }

    @Override
    public ResultInfo updateGoods(Integer id, Goods goods) {
        goods.setId(id);
        int result = goodsDao.updateById(goods);
        if (result == 1) {
            return new ResultInfo().builder().code(StatusCode.OK).message("更新成功").flag(true).build();
        }
        return new ResultInfo().builder().code(StatusCode.ERROR).message("更新失败").flag(false).build();
    }
}
